<template>
  <div class="contentContainer">
    <div class="title">问答列表</div>
    <div v-if="questions.length !== 0" class="questionList">
      <div class="one_QA" v-for="question in questions" :key="question.question_id">
        <QACard :question="question"></QACard>
      </div>
    </div>
    <div class="no_QA" v-else>
      还没有这个关键词相关的问题哦，换个关键词试试吧~
    </div>
  </div>
</template>

<script>
import emitter from "tiny-emitter/instance"
import {useRoute} from 'vue-router'
import {ref, onMounted, onBeforeUnmount} from 'vue'
import WangEditor from "@/components/WangEditor";
import {getAllQuestions} from "@/network/question";
import QACard from "@/components/QACard";
export default {
  name: "Index",
  components: {WangEditor, QACard},
  setup() {
    const searchQuestions = ()=> {
      // 根据关键字过滤
      let searchInfo = route.query['search'];
      if (searchInfo && searchInfo !== "") {
        questions.value = questions.value.filter(question=> {
          return question['question_title'].search(searchInfo) !== -1;
        })
      }
    }

    const updateQuestionList = (questionFilter)=> {
      getAllQuestions().then(res=> {
        questions.value = res.data;
        questionFilter();
      })
    }
    onMounted(()=> {
      // 首先先获取一次问答列表
      updateQuestionList(searchQuestions);
    })

    // 收到信号后更新问题列表
    emitter.on("postQuestion",()=> {
      updateQuestionList(()=>{});
    })
    emitter.on("searchQuestion",()=> {
      updateQuestionList(searchQuestions);
    })
    emitter.on("updateQuestions",()=> {
      updateQuestionList(()=>{});
    })

    onBeforeUnmount( () => {
      // 避免切换路由时重复触发
      emitter.off("postQuestion");
      emitter.off("searchQuestion");
      emitter.off("updateQuestions");
    })

    const route = useRoute();

    const questions = ref([]);

    return {
      questions,
    }
  }

}
</script>

<style scoped lang="scss">
@import "src/assets/scss/common";

.contentContainer {
  width: 80%;
  max-width: 700px;
  margin: 0 auto 30px;
  .title {
    text-align: center;
    font-size: 32px;
    line-height: 2em;
    background: linear-gradient(66.26deg,#771f89 -5.22%,#834cef 46.12%,#636cea 99.41%);
    color: white;
    border-radius: $main-radius $main-radius 0 0;
  }
  .questionList {
    @include simple-shadow();
    .one_QA {
      border-bottom: 1px solid #f1f3f4;
    }
  }
  .no_QA {
    text-align: center;
    font-size: 20px;
    padding: 15px;
    background-color: #f1f3f4;
    color: #707070;
  }
}

</style>
